package com.lagou.worker.service;

import com.lagou.worker.dao.LagouTokenDao;
import com.lagou.worker.model.LagouToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author xsq
 * @Date 2020/7/30 17:55
 **/
@Service
public class UserService {

    @Autowired
    private LagouTokenDao lagouTokenDao;

    private Map<String, String> users = new ConcurrentHashMap();

    /**
     * 用户注册
     *
     * @param email
     * @param password
     */
    public void register(String email, String password) {
        users.put(email, password);
    }

    /**
     * 保存用户token信息
     *
     * @param email
     * @param token
     */
    public void saveToken(String email, String token) {
        LagouToken lagouToke = new LagouToken();
        lagouToke.setEmail(email);
        lagouToke.setToken(token);
        lagouTokenDao.save(lagouToke);
    }

    /**
     * 根据token获取用户信息
     *
     * @param token
     */
    public LagouToken getEmailByToken(String token) {
        return lagouTokenDao.findByToken(token);
    }

    /**
     * 用户登录
     *
     * @param email
     * @param password
     */
    public String login(String email, String password) {
        if (users.containsKey(email)) {
            String dbPassword = users.get(email);
            if (password.equals(dbPassword)) {
                return email;
            } else {
                throw new RuntimeException("密码不正确");
            }
        } else {
            throw new RuntimeException("邮箱未注册");
        }
    }

    public Boolean isRegister(String email) {
        return users.containsKey(email);
    }
}
